/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bombercloud.server;

import bombercloud.commons.GameAction;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 *
 * @author Leonardo Oliveira Moreira
 */
public class BomberCloudServerThread extends Thread {

    private Socket socket;
    private String nodeAddress;
    private int nodePort;

    public BomberCloudServerThread(Socket socket, String nodeAddress, int nodePort) {
        this.socket = socket;
        this.nodeAddress = nodeAddress;
        this.nodePort = nodePort;
    }

    @Override
    public void run() {
        ObjectInputStream inputStream = null;
        ObjectOutputStream outputStream = null;
        if (socket != null && !socket.isClosed()) {
            try {
                outputStream = new ObjectOutputStream(socket.getOutputStream());
                inputStream = new ObjectInputStream(socket.getInputStream());
            } catch (IOException ex) {
                inputStream = null;
                outputStream = null;
            }
        }
        while (socket != null && !socket.isClosed() && inputStream != null && outputStream != null) {
            try {
                GameAction gameAction = (GameAction) inputStream.readObject();
                
                try {
                    Socket nodeSocket = new Socket(nodeAddress, nodePort);
                    if (nodeSocket != null && !nodeSocket.isClosed()) {
                        ObjectInputStream nodeInputStream = new ObjectInputStream(nodeSocket.getInputStream());
                        ObjectOutputStream nodeOutputStream = new ObjectOutputStream(nodeSocket.getOutputStream());
                        nodeOutputStream.writeObject(gameAction);
                        nodeOutputStream.flush();
                        gameAction = (GameAction) nodeInputStream.readObject();
                    }
                    nodeSocket.close();
                } catch (IOException ex) {
                } catch (ClassNotFoundException ex) {
                }

                outputStream.writeObject(gameAction);
                outputStream.flush();
            } catch (IOException ex) {
            } catch (ClassNotFoundException ex) {
            }
        }
        BomberCloudServerOutputMessage.printMessage("The connection was terminated");
    }
}
